package com.petdog.module.recognition.controller;

import com.petdog.common.dto.ApiResponse;
import com.petdog.module.recognition.dto.RecognitionResponse;
import com.petdog.module.recognition.service.RecognitionService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/recognition", "/api/v1/identification"})
@RequiredArgsConstructor
public class RecognitionController {

    private final RecognitionService recognitionService;

    /**
     * 上传图片并进行犬种识别（需要认证）
     */
    @PostMapping("/upload")
    public ApiResponse<RecognitionResponse> uploadAndRecognize(
            @RequestParam("image") MultipartFile imageFile,
            @RequestHeader("Authorization") String token) {
        // 从token中解析userId
        Long userId = parseUserIdFromToken(token);

        try {
            RecognitionResponse response = recognitionService.recognizeDogBreed(imageFile, userId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error("识别失败: " + e.getMessage());
        }
    }

    /**
     * 简单的犬种识别接口（无需认证）
     */
    @PostMapping("/recognize")
    public ApiResponse<RecognitionResponse> recognize(@RequestParam("image") MultipartFile image) {
        try {
            // 使用null作为userId，表示匿名用户
            RecognitionResponse response = recognitionService.recognizeDogBreed(image, null);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error("识别失败: " + e.getMessage());
        }
    }

    /**
     * 获取识别结果
     */
    @GetMapping("/result/{recordId}")
    public ApiResponse<RecognitionResponse> getRecognitionResult(@PathVariable Long recordId) {
        try {
            RecognitionResponse response = recognitionService.getRecognitionResult(recordId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error("获取识别结果失败: " + e.getMessage());
        }
    }

    /**
     * 根据fileId获取识别结果
     * 实现需求文档中的GET /api/v1/identification/result/{fileId}接口
     */
    @GetMapping("/result/{fileId}")
    public ApiResponse<RecognitionResponse> getResultByFileId(@PathVariable String fileId) {
        try {
            RecognitionResponse response = recognitionService.getResultByFileId(fileId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error("获取识别结果失败: " + e.getMessage());
        }
    }

    /**
     * 从JWT token中解析用户ID
     */
    private Long parseUserIdFromToken(String token) {
        // 去掉"Bearer "前缀（如果存在）
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 使用JWT工具类解析token
        // 假设你有一个JwtUtil类，可以解析token并获取用户ID
        // return JwtUtil.parseUserId(token);

        // 示例实现 - 实际应根据你的JWT实现进行调整
        try {
            // 这里应该是你的JWT解析逻辑
            // 例如: return JwtUtil.getUserIdFromToken(token);
            return 1L; // 示例返回值
        } catch (Exception e) {
            throw new RuntimeException("无效的token", e);
        }
    }
}
